package cn.itcast.bos.delivery.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.Access;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.base.action.BaseAction;
import cn.itcast.bos.delivery.service.PromotionService;
import cn.itcast.bos.domain.delivery.Promotion;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion>{
	private File imgFile;
	private String imgFileFileName;
	private File titleImgFile;
	private String titleImgFileFileName;
	@Autowired
	private PromotionService promotionService;
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}
	@Action(value="promotion_upload",results={@Result(type="json",name="success")})
	public String promotion_upload(){
		//获取后缀
		String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
		UUID name = UUID.randomUUID();
		//获取项目真是路径
		String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
		//获取文件存储位置
		String destFile=realPath+"\\"+name+ext;
		System.out.println(destFile);
		//获取项目相对路径
		String contextPath = ServletActionContext.getRequest().getContextPath();
		//获取文件相对路径
		String path=contextPath+"/upload/"+name+ext;
		System.out.println(path);
		try {
			FileUtils.copyFile(imgFile, new File(destFile));
//			 "error" : 0,
//		        "url" : "http://www.example.com/path/to/file.ext"
			//回写信息
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("error", 0);
			map.put("url","http://localhost:8080"+path );
			ActionContext.getContext().getValueStack().push(map);
		} catch (IOException e) {
			Map<String,String> map=new HashMap<String,String>();
			map.put("error", "1");
			map.put("url","上传失败" );
			ActionContext.getContext().getValueStack().push(map);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@Action(value="promotion_manager",results={@Result(name="success",type="json")})
	public String promotion_manager(){
		String realPath = ServletActionContext.getServletContext().getRealPath("/files/");
		File directory = new File(realPath);
		List<Map<String, Object>> fileList = new ArrayList<>();
		if (directory.listFiles() != null) {
			for (File file : directory.listFiles()) {
				Map<String, Object> hash = new HashMap<>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else {
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", true);
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}

		Map<String, Object> result = new HashMap<>();
		result.put("moveup_dir_path", "");
		result.put("current_dir_path", realPath);
		result.put("current_url", ServletActionContext.getRequest().getContextPath() + "/files/");
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
	
	@Action(value="promotion_add",results={@Result(name="success",type="redirect",location="/pages/take_delivery/promotion.html")})
	public String add_promotion(){
		//获取后缀
				String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
				UUID name = UUID.randomUUID();
				//获取项目真是路径
				String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
				//获取文件存储位置
				String destFile=realPath+"\\"+name+ext;
				//获取项目相对路径
				String contextPath = ServletActionContext.getRequest().getContextPath();
				//获取文件相对路径
				String path=contextPath+"/upload/"+name+ext;
				try {
					FileUtils.copyFile(titleImgFile, new File(destFile));
				} catch (IOException e) {
					e.printStackTrace();
				}
				t.setTitleImg(path);
				System.out.println(t);
				promotionService.save(t);
		return SUCCESS;
	}
	
	@Action(value="showPromotion",results={@Result(name="success",type="json")})
	public String showPromotion(){
		System.out.println(page+"-------"+rows);
		Pageable pageable=new PageRequest(page-1, rows);
		Page<Promotion> page=promotionService.showPromotion(pageable);
		List<Promotion> content = page.getContent();
		System.out.println(content+"-------"+page.getTotalElements());
		putIntoValueStack(page);
		return SUCCESS;
	}
}
